import pygame

from lib.sittings import SNAKE_SEGMENT_COLOR, SNAKE_SEGMENT_RADIUS, COLORKEY_COLOR, TILE_SIZE, TILE_RECT, \
    MOVE_VECTORS, MOVE_VECTORS_PIXELS


class Snake_Segment(pygame.sprite.Sprite):
    def __init__(self, tilepos, segment_groups, color=SNAKE_SEGMENT_COLOR, radius=SNAKE_SEGMENT_RADIUS):
        pygame.sprite.Sprite.__init__(self)
        self.image = self.image = pygame.Surface(TILE_SIZE).convert()
        self.image.fill(COLORKEY_COLOR)
        self.image.set_colorkey(COLORKEY_COLOR)
        pygame.draw.circle(self.image, color, TILE_RECT.center, radius)

        self.tilepos = tilepos

        self.rect = self.image.get_rect()
        self.rect.topleft = (tilepos[0] * TILE_SIZE[0], tilepos[1] * TILE_SIZE[1])

        self.segment_groups = segment_groups
        for group in segment_groups:
            group.add(self)

        self.behind_segment = None

        self.movedir = 'left'

    def add_segment(self):
        seg = self
        while True:
            if seg.behind_segment == None:
                x = seg.tilepos[0]
                y = seg.tilepos[1]
                if seg.movedir == 'left':
                    x += 1
                elif seg.movedir == 'right':
                    x -= 1
                elif seg.movedir == 'up':
                    y += 1
                elif seg.movedir == 'down':
                    y -= 1
                seg.behind_segment = Snake_Segment((x, y), seg.segment_groups)
                seg.behind_segment.movedir = seg.movedir
                break
            else:
                seg = seg.behind_segment

    def update(self):
        pass

    def move(self):
        self.tilepos = (
            self.tilepos[0] + MOVE_VECTORS[self.movedir][0], self.tilepos[1] + MOVE_VECTORS[self.movedir][1])
        self.rect.move_ip(MOVE_VECTORS_PIXELS[self.movedir])
        if self.behind_segment is not None:
            self.behind_segment.move()
            self.behind_segment.movedir = self.movedir
